package com.itany.mall.dao.impl;

import java.sql.ResultSet;
import java.util.List;

import com.itany.mall.dao.ProductDao;
import com.itany.mall.dao.mapper.ProductRowMapper;
import com.itany.mall.entity.Product;
import com.itany.mall.factory.Component;
import com.itany.mall.jdbc.template.JDBCTemplate;
import com.itany.mall.jdbc.template.callback.ResultSetExtractor;

@Component
public class ProductDaoImpl implements ProductDao {

	@Override
	public List<Product> selectAll() {
		ProductRowMapper mapper = new ProductRowMapper();
		return new JDBCTemplate<Long, Product>().query(mapper.selectSql(), null, mapper);
	}

	@Override
	public Product selectByName(String name) {
		ProductRowMapper mapper = new ProductRowMapper();
		String sql = mapper.selectSql() + " where p.name = ? ";
		List<Product> list = new JDBCTemplate<Long, Product>().query(sql, new Object[] { name },
				mapper);
		return list != null && list.size() > 0 ? list.get(0) : null;
	}

	@Override
	public void insert(Product p) {
		String sql = " insert into t_product(name, price, num, type_id) values (?, ?, ?, ?) ";
		Object[] params = { p.getName(), p.getPrice(), p.getNum(), p.getTypeId() };
		new JDBCTemplate().update(sql, params);
	}

	@Override
	public Product selectById(long productId) {
		ProductRowMapper mapper = new ProductRowMapper();
		String sql = mapper.selectSql() + " where p.id = ? ";
		List<Product> list = new JDBCTemplate<Long, Product>().query(sql,
				new Object[] { productId }, mapper);
		return list != null && list.size() > 0 ? list.get(0) : null;
	}

	@Override
	public List<Product> findAll(int pageNo, int pageSize) {
		ProductRowMapper mapper = new ProductRowMapper();
		String sql = mapper.selectSql() + " order by p.id limit ?, ? ";
		Object[] params = { (pageNo - 1) * pageSize, pageSize };
		return new JDBCTemplate<Long, Product>().query(sql, params, mapper);
	}

	@Override
	public int selectTotalCount() {
		String sql = " select count(1) from t_product ";
		ResultSetExtractor extractor = new ResultSetExtractor() {
			@Override
			public Object extractData(ResultSet res) throws Exception {
				if (res.next()) {
					return res.getObject(1); // select count查询的数值默认是long类型
				}
				return 0;
			}
		};
		int count = new Long((long) new JDBCTemplate().query(sql, null, extractor)).intValue();
		return count;
	}
}
